package com.thinkgem.jeesite.common.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thinkgem.jeesite.modules.sys.utils.DictUtils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Doc工具类
 * @author fanqinglong
 *
 */
public class DocUtil {
	private static Logger logger = LoggerFactory.getLogger(DocUtil.class);
	
    private static Configuration configuration = null;
    //private static TemplateLoader templateLoader = null;
	static{
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}
	public static String createDoc(HttpServletRequest request,Map<String, Object> data){
		String path = request.getSession().getServletContext().getRealPath("/")+"upload/files/template";
		try {
			configuration.setDirectoryForTemplateLoading(new File(path));
			configuration.setEncoding(Locale.getDefault(), "utf-8");
			//解决空值问题
			configuration.setClassicCompatible(true);
		} catch (IOException e) {
			logger.debug("模板解析路径设置出错");
			return "error:模板解析路径设置出错";
		}
		Template template = null;
		try {
			template = configuration.getTemplate("table.ftl");
		} catch (IOException e) {
			logger.debug("模板读取出错");
			return "error:模板读取出错";
		}
		File savePath = new File(request.getSession().getServletContext().getRealPath("/")+"upload/outFile");
		if (!savePath.exists()) {
			savePath.mkdirs();
		}
		File outFile = new File(savePath, "outFile_"+System.currentTimeMillis()+".doc");
		if (outFile.exists()) {
			outFile.delete();
		}
		Writer writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
		} catch (FileNotFoundException e) {
			logger.debug("IO出错");
			return "error:系统错误";
		} catch (UnsupportedEncodingException e) {
			logger.debug("编码出错");
			return "error:系统错误";
		}
		try {
			template.process(data, writer);
		} catch (TemplateException | IOException e) {
			logger.debug("生成检验报告书出错");
			return "error:生成检验报告书出错";
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				logger.debug("输入流关闭出错");
				return "error:系统错误";
			}
		}
		return outFile.getAbsolutePath();
	}
	public static String createDoc(HttpServletRequest request,String templateURL,Map<String, String> data,String name){
		String path = DictUtils.getDictValue("模板路径", "templatePath", "模板路径");
		if (StringUtils.isBlank(path)) {
			path = "d:\\acs_template\\";
		}
		//String path = request.getSession().getServletContext().getRealPath("/");
		try {
			configuration.setDirectoryForTemplateLoading(new File(path));
			configuration.setEncoding(Locale.getDefault(), "utf-8");
			//解决空值问题
			configuration.setClassicCompatible(true);
		} catch (IOException e) {
			logger.debug("模板解析路径设置出错");
			return "error:模板解析路径设置出错";
		}
		Template template = null;
		try {
			template = configuration.getTemplate(templateURL);
		} catch (IOException e) {
			logger.debug("模板读取出错");
			return "error:模板读取出错";
		}
		File savePath = new File(request.getSession().getServletContext().getRealPath("/")+"upload/outFile");
		if (!savePath.exists()) {
			savePath.mkdirs();
		}
		File outFile = new File(savePath, "outFile_"+(StringUtils.isBlank(name)?templateURL.substring(templateURL.lastIndexOf("/")+1):name)+".doc");
		if (outFile.exists()) {
			outFile.delete();
		}
		Writer writer = null;
		try {
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"utf-8"));
		} catch (FileNotFoundException e) {
			logger.debug("IO出错");
			return "error:系统错误";
		} catch (UnsupportedEncodingException e) {
			logger.debug("编码出错");
			return "error:系统错误";
		}
		try {
			template.process(data, writer);
		} catch (TemplateException | IOException e) {
			logger.debug("生成检验报告书出错");
			return "error:生成检验报告书出错";
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				logger.debug("输入流关闭出错");
				return "error:系统错误";
			}
		}
		return outFile.getAbsolutePath();
	}
	
	public static void main(String[] args) {
		String src = "/upload/files/template/QAU-R-0000002-02（01）   产品退货记录.xml.xml";
		String path = src.substring(0, src.lastIndexOf("/"));
		System.out.println(path+"/"+new Date().getTime()+".ftl");
	}
}
